package com.ilink.groundservice.controller;/**
 * <h3>iLink-java-backend-zhangbo2</h3>
 *
 * @Description <p>【学习广场】-课程学习-学生端与前端的交互接口</p>
 * @Author ZhangBo
 * @Date 2024-09-18 09:26
 **/

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ilink.groundservice.entity.PO.study.course.StudyTeacherCoursesFavorite;
import com.ilink.groundservice.entity.VO.model.ModelHomepageResponse;
import com.ilink.groundservice.entity.VO.study.CourseResponse;
import com.ilink.groundservice.entity.VO.study.NoteCollectionResponse;
import com.ilink.groundservice.entity.VO.study.NoteResponse;
import com.ilink.groundservice.service.Note.DocumentNoteRecordService;
import com.ilink.groundservice.service.Note.VideoNoteRecordService;
import com.ilink.groundservice.service.study.NoteDocumentService;
import com.ilink.groundservice.service.study.NoteVideoService;
import com.ilink.groundservice.service.study.StudyCourseStudentService;
import com.ilink.ilinkapi.dto.ground.model.ModelMetadataRequest;
import com.ilink.ilinkapi.dto.ground.study.CourseMetadataRequest;
import com.ilink.ilinkapi.dto.ground.study.NoteRequest;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.domain.User;
import com.ilink.ilinkcommon.service.oss.OssService;
import com.ilink.ilinkcommon.utils.UserContext;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ilink.ilinkcommon.log.method.MethodLog;
import org.springframework.web.multipart.MultipartFile;

/**
 * @ClassName StudyCourseStudentController
 * @Description 
 * @Author ZhangBo
 * @Date 2024-09-18 09:26
 **/
@Slf4j
@RequestMapping("/ground/study/course")
@RestController
@RequiredArgsConstructor
public class StudyCourseStudentController {
    private final StudyCourseStudentService studyCourseStudentService;
    private final NoteVideoService noteVideoService;
    private final NoteDocumentService noteDocumentService;
    private final OssService ossService;
    private final VideoNoteRecordService videoNoteRecordService;
    private final DocumentNoteRecordService documentNoteRecordService;

    /**
     * @Author ZhangBo
     * @Description 分页返回学习广场课程元数据
     * @Date 10:52 2024/9/18
     * @Param [request]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("分页返回学习广场课程元数据")
    @PostMapping("/get_course_metadata")
    public R getCourseMetadata(@RequestBody CourseMetadataRequest request){
        try {
            String userId = UserContext.getUserId();
            IPage<CourseResponse> responseIPage = studyCourseStudentService
                .getCourseMetadata(userId, request);
            if(responseIPage != null){
                return R.ok("分页返回学习广场课程元数据", responseIPage);
            }else{
                return R.error("未查询到学习广场课程元数据");
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    /**
     * @Author ZhangBo
     * @Description 根据课程id查询学习广场课程信息
     * @Date 14:21 2024/9/18
     * @Param [courseId]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("根据课程id查询学习广场课程信息")
    @GetMapping("/get_course_information_by_id")
    public R getCourseInformationById(@RequestParam("courseId") Long courseId){
        try {
            CourseResponse response = studyCourseStudentService.getCourseInformationById(courseId);
            if(response != null){
                return R.ok("根据课程id查询学习广场课程信息", response);
            }else{
                return R.error("未查询到学习广场课程信息");
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    /**
     * @Author ZhangBo
     * @Description 根据资源id查找资源名称（小链使用）
     * @Date 9:44 2024/9/18
     * @Param [sourceId]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("根据资源id查找资源名称（小链使用）")
    @GetMapping("/get_source_name")
    public R getSourceName(@RequestParam("sourceId") Long sourceId){
        try {
            // 调用 service 方法，获取资源名称和类型
            Map<String, String> sourceInfo = studyCourseStudentService.getSourceName(sourceId);

            if (sourceInfo != null && !sourceInfo.isEmpty()) {
                // 提取 sourceName 和 sourceType
                String sourceName = sourceInfo.get("资源名称");
                String sourceType = sourceInfo.get("类型");

                return R.ok(sourceType, sourceName);
            }
            return R.error("资源名称未找到");
        } catch (Exception e) {
            log.error("函数getSourceName报错: " + e);
            return R.error("获取资源名称失败: " + e.getMessage());
        }
    }

    /**
     * @Author ZhangBo
     * @Description 根据资源id获取资源URL接口
     * @Date 9:59 2024/9/18
     * @Param [sourceId]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("根据资源id获取资源url接口")
    @GetMapping("/get_source_url")
    public R getSourceUrl(@RequestParam("sourceId") Long sourceId){
        try{
            String url = studyCourseStudentService.getSourceUrl(sourceId);
            if(url != null){
                return R.ok("根据资源id获取资源URL", url);
            }
            return R.error("资源URL未找到");
        }catch (Exception e){
            log.error("函数getSourceUrl报错"+e);
            return null;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 根据名称查找视频转写内容
     * @Date 10:03 2024/9/18
     * @Param [objectName]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("根据名称查找视频转写内容")
    @GetMapping("/get_source_url_by_name")
    public R getSourceUrlByName(@RequestParam("objectName") String objectName){
        try{
            String url = studyCourseStudentService.getSourceUrlByObjectName(objectName);
            if(url != null){
                return R.ok("根据名称查找视频转写内容", url);
            }
            return R.error("视频转写内容未找到");
        }catch (Exception e){
            log.error("函数getSourceUrl报错"+e);
            return null;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 点赞
     * @Date 14:29 2024/9/18
     * @Param [jsonString]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("点赞")
    @PostMapping("/add_course_like")
    public R addCourseLike(@RequestBody String jsonString){
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            String courseId = jsonObject.getString("courseId");

            boolean like = studyCourseStudentService.addView(Long.valueOf(courseId));
            if(like){
                return R.ok("点赞量+1");
            }else{
                return R.error("未查询到学习广场课程信息");
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    /**
     * @Author ZhangBo
     * @Description 添加课程到用户收藏夹，仅限一次
     * @Date 14:48 2024/9/18
     * @Param [jsonString]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("添加课程到用户收藏夹")
    @PostMapping("/add_course_collection")
    public R addCourseCollection(@RequestBody String jsonString){
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            String courseId = jsonObject.getString("courseId");

            String userId = UserContext.getUserId();

            String collection = studyCourseStudentService.addFavoriteCourse(userId, courseId);
            if(Objects.equals(collection, "收藏成功")){
                return R.ok("收藏成功");
            }else{
                return R.error("用户已收藏过，跳过插入");
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    /**
     * @Author ZhangBo
     * @Description 取消收藏，仅限一次
     * @Date 14:54 2024/9/18
     * @Param [jsonString]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("取消收藏，仅限一次")
    @PostMapping("/remove_course_collection")
    public R removeCourseCollection(@RequestBody String jsonString){
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            String courseId = jsonObject.getString("courseId");

            String userId = UserContext.getUserId();

            String collection = studyCourseStudentService.removeFavoriteCourse(userId, courseId);
            if(Objects.equals(collection, "取消收藏成功")){
                return R.ok("取消收藏成功");
            }else{
                return R.error("用户未收藏过，跳过删除");
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }
    @MethodLog("获取用户收藏列表")
    @GetMapping("/get_favorite_list")
    public R getFavoriteList() {
        try{
            String userId = UserContext.getUserId();

            List<StudyTeacherCoursesFavorite> favoriteList = studyCourseStudentService.
                getFavoriteListByUserId(userId);
            if(favoriteList != null){
                return R.ok("用户的收藏列表",favoriteList);
            }
            return R.error("用户未收藏课程");
        }catch (Exception e){
            return R.error("获取用户的收藏列表错误"+e.getMessage());
        }
    }
    @MethodLog("获取最常见的课程标签，最多返回8个")
    @GetMapping("/get_common_course_tags")
    public R getCommonCourseTags(){
        try {
            int num = 8;
            return R.ok(studyCourseStudentService.getCommonTags(num));
        } catch(Exception e){
            return R.error("错误：" + e);
        }
    }

    /**
     * @Author ZhangBo
     * @Description 保存课程资源笔记
     * @Date 16:59 2024/10/18
     * @Param [noteRequest]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("保存课程资源笔记")
    @PostMapping("/save_note")
    public R saveNote(@RequestBody NoteRequest noteRequest){
        try{
            String userId = UserContext.getUserId();
            if(noteRequest.getType().equals("音视频资源")){
                boolean isSaved = noteVideoService.saveNoteVideo(userId, noteRequest);
                if (isSaved) {
                    return R.ok("视频笔记保存成功");
                } else {
                    return R.error("视频笔记保存失败");
                }
            } else if (noteRequest.getType().equals("资源")) {
                boolean isSaved = noteDocumentService.saveNoteDocument(userId, noteRequest);
                if (isSaved) {
                    return R.ok("文档笔记保存成功");
                } else {
                    return R.error("文档笔记保存失败");
                }
            }
            return R.error("笔记查找类型错误");
        }catch (Exception e){
            return R.error("笔记保存错误：" + e);
        }
    }

    /**
     * @Author ZhangBo
     * @Description 获取课程资源笔记
     * @Date 10:48 2024/10/16
     * @Param [noteRequest]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("获取课程资源笔记")
    @PostMapping("/get_note")
    public R getNote(@RequestBody NoteRequest noteRequest) {
        try{
            String userId = UserContext.getUserId();
            if(noteRequest.getType().equals("音视频资源")){
                return noteVideoService.getNoteVideo(noteRequest.getSourceId(), userId);
            } else if (noteRequest.getType().equals("资源")) {
                return noteDocumentService.getNoteDocument(noteRequest.getSourceId(), userId);
            }
            return R.error("笔记查找类型错误");
        }catch (Exception e){
            return R.error("笔记保存错误：" + e);
        }
    }

    /**
     * @Author ZhangBo
     * @Description 获取教师创建的所有课程的笔记
     * @Date 9:45 2024/10/20
     * @Param []
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("获取教师创建的所有课程的笔记")
    @PostMapping("/get_notes_by_course")
    public R getNotesByCourse(@RequestBody String jsonString){
        try{
            JSONObject jsonObject = new JSONObject(jsonString);
            String courseId = jsonObject.getString("courseId");

            List<NoteCollectionResponse> responses = studyCourseStudentService.getAllNotesByTeacher(courseId);
            if(responses != null){
                return R.ok("教师创建的所有课程的笔记", responses);
            }
            return R.error("未查询到该教师创建课程的笔记");
        }catch (Exception e){
            return R.error("获取所有笔记错误：" + e);
        }
    }

    @MethodLog("上传文件并获取URL")
    @PostMapping("/uploadAndGetUrl")
    public R uploadFileAndGetUrl(@RequestParam("file") MultipartFile file,
        @RequestParam("bucketName") String bucketName,
        @RequestParam("objectName") String objectName) {
        try {
            // 调用服务层的上传和获取URL方法
            String fileUrl = ossService.uploadFileAndGetUrl(file, bucketName, objectName);
            if (fileUrl != null) {
                return R.ok("文件上传并获取URL成功", fileUrl);
            } else {
                return R.error("文件上传或获取URL失败");
            }
        } catch (Exception e) {
            return R.error("文件上传或获取URL错误: " + e.getMessage());
        }
    }

    /**
     * @Author lrh
     * @Description 教师端大屏获取课程视频资源笔记
     * @Date 19：10 2024/12/13
     * @Param [courseId]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("教师端大屏获取视频笔记")
    @GetMapping("/getNoteVideoRecord")
    public R getNoteVideoRecord(@RequestParam(required = false) Long courseId){
        try{
           return videoNoteRecordService.getNoteRecord(courseId);
        }catch (Exception e){
            return R.error("查询笔记记录错误" + e);
        }
    }

    @MethodLog("教师端大屏获取文档笔记")
    @GetMapping("/getNoteDocumentRecord")
    public R getNoteDocumentRecord(@RequestParam(required = false) Long courseId){
        try{
            return documentNoteRecordService.getNoteRecord(courseId);
        }catch (Exception e){
            return R.error("查询笔记记录错误" + e);
        }
    }
}
